var app = getApp();

function formatTime(date) {
  var year = date.getFullYear();
  var month = date.getMonth() + 1;
  var day = date.getDate();
  var hour = date.getHours();
  var minute = date.getMinutes();
  var second = date.getSeconds();
  return [year, month, day].map(formatNumber).join('/') + ' ' + [hour, minute, second].map(formatNumber).join(':');
}

function formatNumber(n) {
  n = n.toString();
  return n[1] ? n : '0' + n;
}

// 获取customer_id的值
function getCustomerId() {
  return wx.getStorageSync('customer_id').customer_id;
}

// 时间转为时分秒
function sec_to_time(s) {
  var t;
  if (s > -1) {
    var hour = Math.floor(s / 3600);
    var min = Math.floor(s / 60) % 60;
    var sec = s % 60;
    if (hour < 10) {
      t = '0' + hour + ':';
    } else {
      t = hour + ':';
    }

    if (min < 10) {
      t += '0';
    }
    t += min + ':';
    if (sec < 10) {
      t += '0';
    }
    t += sec.toFixed(0);
  }
  return t;
}

// 登录页面
const getUserInfo = function (app, cb) {
  wx.login({
    success : function () {
      wx.getUserInfo({
        success : function (res) {
          let detail = res.userInfo;

          wx.request({
            method : 'POST',
            url : app.globalData.urls + '/order/update',///user/wxapp/register/complex
            data : {
              customer_id : cb.customer_id,
              nickName : detail.nickName,
              avatarUrl : detail.avatarUrl,
              gender : detail.gender
            },
            success : function (res) {
              if (res.data.code != 0 && res.data.code != 200) {
                // wx.showModal({
                //   title: '温馨提示',
                //   content: '需要您的授权，才能正常使用哦～',
                //   showCancel: false,
                //   success: function (res) { }
                // })
              } else {
                // app.login();
                // wx.showToast({
                //   title: '授权成功',
                //   duration: 2000
                // })
                wx.setStorage({
                  key : 'userInfo',
                  data : detail
                });
                app.globalData.userInfo = detail;
                wx.showTabBar();
              }
            }
          });


        }
      });
    }
  });
};

const loginAccount = function (app, callback) {
  wx.showLoading({
    title : '正在登录...',
  });

  wx.request({
    url : app.globalData.urls + '/customer/login/wxindex',
    header : app.getRequestHeader(),
    data : {
      bdmin_user_id : share_bdmin_user_id() || ''
    },
    success : function (res) {
      if (res.data.code == 200) {
        wxLogin(app, callback);
      } else {
        let data = res.data.data;
        // if(!data.head_url||!data.phone){
        //   wx.navigateTo({
        //     url: "/pages/login/login"
        //   })
        // }else{
        // }
        let userInfo = wx.getStorageSync('userInfo');

        if (!((data.head_url != '' || userInfo))) {
          wx.navigateTo({
            url : '/pages/login/login'
          });
        }
        callback();
        wx.hideLoading();
      }
    }
  });
};
var wxLogin = function (app, callback) {
  var that = this;
  wx.login({
    success : function (res) {
      wx.request({
        url : app.globalData.urls + '/customer/login/wxcode',  // "/user/wxapp/login",
        header : app.getPostRequestHeader(),
        method : 'POST',
        data : {
          code : res.code,
          bdmin_user_id : share_bdmin_user_id() || ''
        },
        success : function (res) {
          // if(type){
          //   wx.showLoading({
          //     title: "正在登录...",
          //   })
          // }
          // wx.showLoading({
          //   title: "正在登录...",
          // })
          loginAccount(app, callback);

          app.saveReponseHeader(res);

        }
      });
    }
  });
};
var formatDateTime = function (inputTime) {
  var date = new Date(inputTime);
  var y = date.getFullYear();
  var m = date.getMonth() + 1;
  m = m < 10 ? ('0' + m) : m;
  var d = date.getDate();
  d = d < 10 ? ('0' + d) : d;
  var h = date.getHours();
  h = h < 10 ? ('0' + h) : h;
  var minute = date.getMinutes();
  var second = date.getSeconds();
  minute = minute < 10 ? ('0' + minute) : minute;
  second = second < 10 ? ('0' + second) : second;
  return y + '-' + m + '-' + d + ' ' + h + ':' + minute + ':' + second;
};

// 获取多商户id
var getBdmin_user_id = function () {
  var customer_id = wx.getStorageSync('customer_id');
  return customer_id.bdmin_user_id;
};
// 分享出去的商户id
var share_bdmin_user_id = function () {
  return wx.getStorageSync('shareId') || 3;
};
// 获取store_id
var getStore_id = function () {
  var customer_id = wx.getStorageSync('customer_id');
  return customer_id.store_id;
};
// 添加店铺浏览记录
var storeBrower = function (app) {
  let customer_id = wx.getStorageSync('customer_id');
  if (!customer_id.wx_openid) return;
  //4个热销广告位
  wx.request({
    url : app.globalData.urls + '/index/store-brose',
    header : app.getRequestHeader(),
    method : 'POST',
    data : {
      open_id : customer_id.wx_openid,
      bdmin_user_id : share_bdmin_user_id()
    },
    success : function (res) {
    }
  });
};

// 用户行为分析-埋点
var stat = function (app, page, type) {
  let customer_id = wx.getStorageSync('customer_id');
  wx.request({
    url : app.globalData.urls + '/index/path',
    header : app.getRequestHeader(),
    method : 'POST',
    data : {
      page,
      type,//1直接访问，2通过分享页面，3通过直播页面
      unit_id : new Date(),
      customer_id : customer_id.customer_id,
      bdmin_user_id : share_bdmin_user_id()
    },
    success : function (res) {}
  });
};
// 清空登录信息
var clearLogin = function (id) {
  if (id != share_bdmin_user_id()) {
    wx.clearStorageSync('userInfo');
    wx.clearStorageSync('customer_id');
  }
  wx.setStorageSync('shareId', id);
};

const copyText = function (data) {
  wx.setClipboardData({
    data : data,
    success : function (res) {
      wx.getClipboardData({
        success : function () { }
      });
    }
  });
};
module.exports = {
  copyText,
  formatTime : formatTime,
  getCustomerId,
  sec_to_time,
  getUserInfo,
  loginAccount,
  formatDateTime,
  getBdmin_user_id,
  getStore_id,
  share_bdmin_user_id,
  storeBrower,
  clearLogin,
  stat,
  version : '1.0.0'
};
